<template>
  <div style="padding: 0 20px">
    <div class="searchForm_box">
      <el-form ref="searchForm" :inline="true" size="mini" :model="searchForm">
        <el-form-item label="项目名称：" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="行业：" prop="industry_id">
          <el-select v-model="searchForm.industry_id" filterable clearable placeholder="请选择客户行业">
            <el-option
              v-for="item in industry_dict"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
				<el-form-item label="维护人：" prop="maintenance_staff_id">
					<el-select v-model="searchForm.maintenance_staff_id" filterable clearable placeholder="请选择维护人" style="width: 100%">
					  <el-option
					    v-for="item in user_list"
					    :key="item.id"
					    :label="item.name"
					    :value="item.id"
					    :disabled="item.status === 0"
					  />
					</el-select>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetForm('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="data_box">
      <el-table size="mini" v-loading="tableLoading" :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="150"/>
        <el-table-column prop="address" label="地址" width="150"/>
        <el-table-column prop="industry_name" label="行业" width="150"/>
        <el-table-column prop="maintenance_staff_name" label="当前维护人员" width="150"/>
        <el-table-column label="漏斗信息" min-width="200">
          <template slot-scope="scope">
            {{ getFunnelsName(scope.row.funnels) }}
          </template>
        </el-table-column>
        <el-table-column prop="contract_amount" label="合同总金额(元)" width="150"></el-table-column>
        <el-table-column fixed="right" label="操作" width="400px">
          <template slot-scope="scope">
            <div style="text-align: center">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCustomer(scope.row.id)"
                         v-permission="'customer_edit'"
              >变更客户信息
              </el-button>
              <el-button type="primary" size="mini" v-permission="'customer_manage_look'" @click="lookCustomer(scope.row)">查看客户详细信息</el-button>
              <el-button type="primary" size="mini" @click="showAssignDialog(scope.row)">指派人员</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page.sync="searchForm.page"
      :page-sizes="[10, 20, 50, 100,200,500]"
      :page-size.sync="searchForm.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!--对话框-->
    <el-dialog title="申请列表" :visible.sync="flowDialogVisible" center width="80%" @close="closeDialog">
      <div class="searchForm_box">
        <el-form ref="flowSearchForm" :inline="true" :model="flowListParams">
          <el-form-item label="客户名称：" prop="name">
            <el-input v-model="flowListParams.name" placeholder="请输入客户名称"/>
          </el-form-item>
          <el-form-item label="行业：" prop="industry_id">
            <el-select v-model="flowListParams.industry_id" placeholder="请选择客户行业">
              <el-option
                v-for="item in industry_dict"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="flowSearch">搜索</el-button>
            <el-button @click="resetForm('flowSearchForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="flowTableLoading" :data="flowTableData" border>
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scope">
            <span>{{ (listParams.page - 1) * listParams.page_size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="150"/>
        <el-table-column label="申请类型" width="150">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.created == 0">跟进报备</el-tag>
            <el-tag v-else type="success">新客户报备</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.flow_status == 3">审批中</el-tag>
            <el-tag v-else-if="scope.row.flow_status == 4" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.flow_status == 2" type="danger">驳回</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" width="200">
          <template slot-scope="scope">
            {{ scope.row.created_at }}
          </template>
        </el-table-column>
        <el-table-column prop="apply_name" label="申请人" width="100"/>
        <el-table-column prop="address" label="地址" width="150"/>
        <el-table-column prop="industry_name" label="行业" width="150"/>
        <el-table-column prop="maintenance_staff_name" label="当前维护人员" width="150"/>
        <el-table-column label="漏斗信息" min-width="200">
          <template slot-scope="scope">
            {{ getFunnelsName(scope.row.funnels) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" center label="操作" width="150px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="seeCustomerInfo(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="flowListParams.page"
        :page-sizes="[10, 20, 50, 100,200,500]"
        :page-size="flowListParams.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="flowTotal"
        @size-change="flowHandleSizeChange"
        @current-change="flowHandleCurrentChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="flowDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="指派销售人员" :visible.sync="assignDialogVisible" center width="20%" @close="closeAssignDialog">
      <el-form ref="updateForm" :model="updateForm" :rules="rules">
        <el-form-item label="销售人员" style="margin: 0px auto;width: 90%" prop="maintenance_staff_id">
          <el-select v-model="updateForm.maintenance_staff_id" placeholder="请选择销售">
            <el-option
              v-for="item in salasList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="margin-top: 10px">
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { edit, page as list } from '@/api/customer/customer'
import { draftsIsNull, getFlowCheckCount, page as flowList } from '@/api/customer/customerFlow'
import { list_all3rd_bycode } from '@/api/business/setting/dict'
import { getSubordinateUser, allList as allUserList } from '@/api/system/user'
import { generateUUID } from '@/utils/util'

export default {
  name: 'Index',
  data() {
    return {
      searchForm: {
        name: null,
        industry_id: null,
        page: 1,
        page_size: 10,
        is_my_customer_page: false,
		maintenance_staff_id: null,
      },
      listParams: {
        name: null,
        industry_id: null,
        page: 1,
        page_size: 10,
        is_my_customer_page: false,
		maintenance_staff_id: null,
      },
      flowListParams: {
        name: null,
        industry_id: null,
        page: 1,
        page_size: 10,
        is_my_customer_page: false,
		maintenance_staff_id: null,
      },
      updateForm: {
        id: null,
        maintenance_staff_id: null
      },
      total: null,
      flowTotal: null,
      tableData: [], // 客户信息
      industry_dict: [], // 行业字典
      flowTableData: [], // 申请信息
      flowDialogVisible: false,
      tableLoading: false,
      flowTableLoading: false,
      count: 0,
      salasList: [],
			user_list: [],
      assignDialogVisible: false,
      rules: {
        maintenance_staff_id: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.initIndustryDict()
    this.getList()
    // this.getFlowCheckCount()
    this.initUsers()
	this.initUserList();
  },
  methods: {
		/**
		 * 初始化用户数据
		 */
		initUserList() {
		  allUserList().then(res => {
		    this.user_list = res.data
		  })
		},
    async getFlowCheckCount() {
      await getFlowCheckCount({ is_my_customer_page: false }).then(
        res => {
          this.count = res.data
        }
      )
    },
    seeCustomerInfo(row) {
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          flow_id: row.id
        }
      })
      this.$router.push({
        name: 'customer_reporting',
        query: {
          uuid: uuid
        }
      })
    },
    closeAssignDialog() {
      this.updateForm = {
        id: null,
        maintenance_staff_id: null
      }
    },
    edit() {
      this.$refs['updateForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          edit(this.updateForm).then(
            res => {
              if (res.data) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
              } else {
                this.$message.error('操作失败')
              }
              loading.close()
              this.getList()
            }
          ).catch(() => {
            loading.close()
          })
          this.assignDialogVisible = false
        }
      })
    },
    showAssignDialog(row) {
      this.assignDialogVisible = true
      this.updateForm.id = row.id
      this.$nextTick(() => {
        this.$refs['updateForm'].clearValidate()
      })
    },
    lookCustomer(row) {
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          customer_id: row.id,
          disabled: true,
          showCreateTAble: true
        }
      })
      this.$router.push({
        name: 'customer_manage_look_page',
        query: {
          uuid: uuid
        }
      })
    },
    initUsers() {
      getSubordinateUser().then(
        res => {
          this.salasList = res.data.map(
            item => (
              {
                id: item.id,
                name: item.name
              }
            )
          )
        }
      )
    },
    search() {
      this.searchForm.page = 1
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    flowSearch() {
      this.getFlowList()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.listParams = Object.assign({}, this.searchForm)
      if (formName == 'searchForm') {
        this.getList()
      } else {
        this.getFlowList()
      }
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    flowHandleSizeChange(val) {
      this.flowListParams.page_size = val
      this.getFlowList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    flowHandleCurrentChange(val) {
      this.flowListParams.page = val
      this.getFlowList()
    },
    getList() {
      this.tableLoading = true
      list(this.listParams).then(
        res => {
          this.tableLoading = false
          this.tableData = res.data.records
          this.total = res.data.total
        }
      ).catch(() => {
        this.tableLoading = false
      })
    },
    getFlowList() {
      this.flowTableLoading = true
      flowList(this.flowListParams).then(
        res => {
          this.flowTableLoading = false
          this.flowTableData = res.data.records
          this.flowTotal = res.data.total
        }
      ).catch(() => {
        this.flowTableLoading = false
      })
    },
    // 初始化行业字典
    initIndustryDict() {
      list_all3rd_bycode({ code: 'khxg-hy' }).then(
        res => {
          this.industry_dict = res.data.map(item => (
            {
              id: item.id,
              name: item.name
            }
          ))
        }
      )
    },
    // 获取漏斗信息
    getFunnelsName(funnels) {
      if (funnels && funnels.length > 0) {
        let str = ''
        for (let i = 0; i < funnels.length; i++) {
          if (i != funnels.length - 1) {
            str += funnels[i].funnel_type_name + ','
          } else {
            str += funnels[i].funnel_type_name
          }
        }
        return str
      } else {
        return ''
      }
    },
    // 关闭弹框
    closeDialog() {
      this.flowListParams = {
        name: null,
        industry_id: null,
        page: 1,
        page_size: 10,
        is_my_customer_page: true
      }
    },
    showDialog() {
      this.flowDialogVisible = true
      this.getFlowList()
    },
    async draftsIsNull() {
      let tmp = -2
      await draftsIsNull().then(
        res => {
          tmp = res.data
        }
      ).catch(
        () => {
          tmp = -1
        }
      )
      return tmp
    },
    editCustomer(id) {
      const uuid = generateUUID()
      this.$store.commit('keep/PUT_PAGE_PARAMS', {
        uuid: uuid,
        data: {
          customer_id: id,
          edit: true,
          showCreateTAble: true
        }
      })
      this.$router.push({
        name: 'customer_edit_page',
        query: {
          uuid: uuid
        }
      })
    }
  }
}
</script>

<style scoped>
.searchForm_box {
  margin-top: 20px;
  margin-left: 10px;
}

.data_box {
  margin-left: 10px;
}

.el-table {
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
}

.el-badge {
  left: 10px;
  top: -1px;
}

/deep/ .el-dialog__footer {
  margin-top: 10px;
}
</style>
